springboot的功能逐渐强大,除了可以给图片加水印以外,还能给图片加上二维码,支持私人订制,哈哈哈哈,废话不多说,直接上代码

首先是引入依赖,gradle是引入下面这两个,maven引入自行搜索

1
2
compile("com.google.zxing:core:3.4.0")
compile("com.google.zxing:javase:3.4.0")

然后进入正文

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
@PostMapping("/watermarkImages")
public String watermarkImages() throws Exception {
//获取原始图片文件
String srcImgPath = "F://bg1.png";
String fileNameType = srcImgPath.substring(srcImgPath.lastIndexOf("."), srcImgPath.length());
String tarImgPath = CustomConfig.diskLocation + System.currentTimeMillis() + fileNameType; //待存储的地址
addWaterMark(srcImgPath, tarImgPath);
return "success";
}

/***
* 在一张背景图上添加二维码
* @param bigImgPath 背景图的路径
* @param outPathWithFileName 输出路径
*/
public void addWaterMark(String bigImgPath, String outPathWithFileName) throws Exception {
// 读取原图片信息
File srcImgFile = new File(bigImgPath);//得到文件
Image srcImg = ImageIO.read(srcImgFile);//文件转化为图片
int srcImgWidth = srcImg.getWidth(null);//获取图片的宽
int srcImgHeight = srcImg.getHeight(null);//获取图片的高
// 加水印
BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bufImg.createGraphics();
g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
String content = "时光蹉跎看淡岁月你我";
//使用工具类生成二维码
Image image = QRCodeUtil.createImages(content);
//将小图片绘到大图片上,500,300 .表示你的小图片在大图片上的位置。
g.drawImage(image, 500, 500, null);
//设置颜色。
g.setColor(Color.WHITE);
g.dispose();
// 输出图片
FileOutputStream outImgStream = new FileOutputStream(outPathWithFileName);
ImageIO.write(bufImg, "png", outImgStream);
System.out.println("添加水印完成");
outImgStream.flush();
outImgStream.close();
}


/***
* 生成二维码
* @param content 二维码里面的内容
*/
public static BufferedImage createImages(String content) throws Exception {
Hashtable hints = new Hashtable();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, 192, 192, hints);
int width = bitMatrix.getWidth();
int height = bitMatrix.getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
}
}
return image;
}